package com.yociyy.auth.controller;

import com.yociyy.admin.feign.RemoteUserService;
import com.yociyy.admin.model.entity.BaseUser;
import com.yociyy.auth.biz.AuthBiz;
import com.yociyy.auth.entity.LoginForm;
import com.yociyy.auth.service.IAuthTokenService;
import com.yociyy.common.core.msg.R;
import com.yociyy.security.authentication.YoCiUser;
import com.yociyy.security.utils.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * 用户验证
 * 
 * @author: YoCiyy
 * @date: 2020/4/15
 */
@RestController
@RequestMapping("auth")
@RequiredArgsConstructor
@Slf4j
public class AuthTokenController {

	private final AuthBiz authBiz;

	private final RemoteUserService remoteUserService;

	private final IAuthTokenService authTokenService;

	@PostMapping("/user/token")
	public R loginByForm(String username, String password, HttpServletRequest request, HttpServletResponse response) throws IOException {

		ServletWebRequest webRequest = new ServletWebRequest(request, response);
		Map<String, Object> map = authTokenService.authenticationByForm(username, password, webRequest);
		return R.success(map);
	}

	/**
	 * 用户登录
	 * 
	 * @param login 登录账号 登录密码
	 * @return 结果
	 */
	@PostMapping("/login")
	public R login(@RequestBody LoginForm login) {
		// 校验用户登录
		BaseUser user = authBiz.login(login.getUsername(), login.getPassword());
		// 创建token
		return R.success(authBiz.createAccessToken(user));
	}

	/**
	 * 用户注销登录、移除token信息
	 * 
	 * @param request token信息
	 * @return 结果
	 */
	 @PostMapping("/logout")
	public R logout(HttpServletRequest request) {
//		String token = request.getHeader("Access-Token");
//		BaseUser user = authBiz.queryByToken(token);
//
//		if (ObjectUtil.isNotEmpty(user)) {
//			authBiz.expireToken(user.getId());
//		}
		return R.success();
	}

	/**
	 * 当前登录用户信息
	 *
	 * @param request 请求
	 * @return 用户信息
	 */
	@GetMapping("/user/info")
	public R currUser(HttpServletRequest request) {
		YoCiUser user = SecurityUtils.getUser();
		return R.success(remoteUserService.selectLoginUser(user.getId()));
	}
}
